const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
const fs = require('fs');

const app = express();
const server = http.Server(app);
const io = socketIo(server);

const configPath = process.pkg ? path.join(path.dirname(process.execPath), 'config.json') : path.join(__dirname, 'config.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));

app.set('view engine', 'ejs');
app.use("/", express.static(path.join(__dirname, 'html')));

let list = [];

app.get("/getlist", function (req, res) {
    let username = req.query.username;
    let userData = searchUser(username);
    if (userData) {
        res.json({
            code: 200,
            data: list[userData[1]].chatList
        });
    } else {
        res.json({
            code: 403,
            msg: '该用户不存在'
        });
    }
});

app.get("/new", function (req, res) {
    let username = req.query.username;
    if (username) {
        if (list.findIndex((item) => item.username == username) !== -1) {
            res.json({
                code: 403,
                msg: '该用户名已被使用'
            });
            return;
        }
        list.push({
            username: username,
            chatList: []
        });
        console.log("新用户注册了", username);

        io.emit('new', username);
        res.json({
            code: 200,
            msg: 'ok'
        });
    }
});

app.get("/alluser", function (req, res) {
    let arr = [];
    for (let i = 0; i < list.length; i++) {
        arr.push(list[i].username);
    }
    res.json({
        code: 200,
        data: arr
    });
});

io.on('connection', function (socket) {
    console.log('有人连接了');
    socket.on('disconnect', function () {
        console.log('有人断开连接了');
    });
    socket.on('sand', function (msg) {
        let userData = searchUser(msg.username);
        if (userData) {
            let data = {
                from: msg.from,
                content: msg.content,
                id: getRandomString(10),
                isCom: false,
                time: new Date().getTime(),
                user: msg.username
            };
            list[userData[1]].chatList.push(data);
            if (msg.from == "user") {
                let di = getRandomString(10);
                let dat = {
                    from: "ai",
                    content: "",
                    id: di,
                    isCom: true,
                    time: new Date().getTime(),
                    user: msg.username
                };
                list[userData[1]].chatList.push(dat);
                io.emit('sand', [[data, dat], list[userData[1]].chatList, di]);
            } else {
                io.emit('sand', [[data], list[userData[1]].chatList]);
            }
        } else {
            io.emit('sand', [{ code: 403, msg: '该用户不存在' }]);
        }
    });

    socket.on('change', function (msg) {
        let userData = searchUser(msg.username);
        if (userData) {
            if (msg.from == "ai") {
                let id = msg.id;
                for (let i = 0; i < list[userData[1]].chatList.length; i++) {
                    if (list[userData[1]].chatList[i].id == id) {
                        list[userData[1]].chatList[i].content = msg.content;
                        let dd = list[userData[1]].chatList[i];
                        dd.user = msg.username;
                        io.emit('change', [dd, msg.speed]);
                        break;
                    }
                }
            }
        } else {
            io.emit('sand', [{ code: 403, msg: '该用户不存在' }]);
        }
    });
});

function getRandomString(length) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    let result = '';
    const charLength = chars.length;
    for (let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * charLength));
    }
    return result;
}

function searchUser(username) {
    if (!username) {
        return;
    }
    let isPass = false;
    for (let i = 0; i < list.length; i++) {
        if (list[i].username == username) {
            return [list[i], i];
        } else {
            isPass = true;
        }
    }
    if (isPass) {
        return null;
    }
}

server.listen(config.port, '127.0.0.1', function (e) {
    console.log("服务器启动成功");
});
